﻿using System;
using System.Linq;
using System.Xml;

namespace HuaXingSDK
{
    public abstract class HXXml : EntityToXml
    {
        private const string ROOT = "Document";
        private const string HEADER = "header";
        private const string BODY = "body";

        protected abstract string[] GetHeader();

        protected abstract string[] GetBody();

        protected override string GetRootName()
        {
            return ROOT;
        }

        public override XmlDocument ToXml()
        {
            var xml = base.ToXml();
            var root = xml.DocumentElement;
            if (root == null)
                throw new HXException("Xml中没有根节点。");

            xml.PrependChild(xml.CreateXmlDeclaration("1.0", "utf-8", ""));

            var header = root.AppendChild(CreateXmlNode(HEADER));
            var body = root.AppendChild(CreateXmlNode(BODY));
            var hname = GetHeader();
            var bname = GetBody();

            foreach (var node in root.ChildNodes.ToArray())
            {
                if (hname.Any(i => i.Equals(node.Name, StringComparison.OrdinalIgnoreCase)))
                {
                    header.AppendChild(node);
                }
                else if (bname.Any(i => i.Equals(node.Name, StringComparison.OrdinalIgnoreCase)))
                {
                    body.AppendChild(node);
                }
            }
            return xml;
        }
    }
}
